package com.example.administrator.bttest;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;


public class MyActivity extends Activity {
    Button up;
    Button down;
    Button left;
    Button right;
    Button stop;
    String command = null;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothDevice mDevice=null;
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    private InputStream inStream = null;

    private static final UUID MY_UUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static String address = "98:D3:31:20:16:C2";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        command="0";
        up = (Button) findViewById(R.id.button);
        down = (Button) findViewById(R.id.button2);
        left = (Button) findViewById(R.id.button3);
        right = (Button) findViewById(R.id.button4);
        stop = (Button) findViewById(R.id.button5);

        up.setOnClickListener(new View.OnClickListener() {
                                  //@Override
                                  public void onClick(View v) {
                                      command = "1";
                                      byte[] msgBuffer;
                                      try {
                                          outStream = btSocket.getOutputStream();

                                      } catch (IOException e) {;}
                                      msgBuffer = command.getBytes();
                                      try {
                                          outStream.write(msgBuffer);
                                      } catch (IOException e) {;}
                                  }
                              });

        down.setOnClickListener(new View.OnClickListener() {
            //@Override
            public void onClick(View v) {
                command = "2";
                byte[] msgBuffer;
                try {
                    outStream = btSocket.getOutputStream();

                } catch (IOException e) {;}
                msgBuffer = command.getBytes();
                try {
                    outStream.write(msgBuffer);
                } catch (IOException e) {;}
            }
        });

        left.setOnClickListener(new View.OnClickListener() {
            //@Override
            public void onClick(View v) {
                command = "3";
                byte[] msgBuffer;
                try {
                    outStream = btSocket.getOutputStream();

                } catch (IOException e) {;}
                msgBuffer = command.getBytes();
                try {
                    outStream.write(msgBuffer);
                } catch (IOException e) {;}
            }
        });

        right.setOnClickListener(new View.OnClickListener() {
            //@Override
            public void onClick(View v) {
                command = "4";
                byte[] msgBuffer;
                try {
                    outStream = btSocket.getOutputStream();

                } catch (IOException e) {;}
                msgBuffer = command.getBytes();
                try {
                    outStream.write(msgBuffer);
                } catch (IOException e) {;}
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            //@Override
            public void onClick(View v) {
                command = "0";
                byte[] msgBuffer;
                try {
                    outStream = btSocket.getOutputStream();

                } catch (IOException e) {;}
                msgBuffer = command.getBytes();
                try {
                    outStream.write(msgBuffer);
                } catch (IOException e) {;}
            }
        });

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "还是没有", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(mIntent, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "不允许蓝牙开启", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        DisplayToast("正在尝试连接智能小车，请稍后····");
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        for(BluetoothDevice d : pairedDevices){
            if(d.getName().equals("HC-06")){
                mDevice=d;
                Log.e("App", d.getName());
                break;
            }
        }
        try {
            btSocket = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            DisplayToast("套接字创建失败！");
        }
        DisplayToast("成功连接智能小车！可以开始操控了~~~");
        mBluetoothAdapter.cancelDiscovery();
        try {
            btSocket.connect();
            DisplayToast("连接成功建立，数据连接打开！");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                DisplayToast("连接没有建立，无法关闭套接字！");
            }
        }

    }

    @Override
    public void onPause() {

        super.onPause();
        command="0";
        try {
            outStream = btSocket.getOutputStream();
        } catch (IOException e) {;}
        byte[] msgBuffer = command.getBytes();
        try {
            outStream.write(msgBuffer);
        } catch (IOException e) {;}

        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {;}

        }

        try {
            btSocket.close();
        } catch (IOException e2) {

            DisplayToast("套接字关闭失败！");
        }

    }



    public void DisplayToast(String str) {
        Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 0, 220);
        toast.show();
    }
}
